<template>
  <div class="pc clearfix"  @drop='dropTemplate($event)' @dragover.prevent>
    <div class="pc-left" ondragover='window.event.preventDefault()' ondrop='window.event.stopPropagation()'>
      <div class="l-head">控件(鼠标拖动至右侧即可使用)</div>
      <div class="l-item" draggable="true"  @dragstart='dragTemplate($event, "banner")'>
        <div class="l-title">Banner</div>
        <img src="../../assets/floor/banner.png" alt="">
        <div class="l-text" style="margin-bottom: 0;">banner</div>
      </div>
      <div class="l-item">
        <div class="l-title">楼层</div>
        <div draggable="true" class="l-content" @dragstart='dragTemplate($event, wideTemplate[0])'>
          <img src="../../assets/floor/three.png" alt="">
          <div class="l-text">多广告</div>
        </div>
        <div draggable="true" class="l-content" @dragstart='dragTemplate($event, wideTemplate[1])'>
          <img src="../../assets/floor/more.png" alt="">
          <div class="l-text">潮流新款</div>
        </div>
        <div draggable="true" class="l-content" @dragstart='dragTemplate($event, wideTemplate[2])'>
          <img src="../../assets/floor/long.png" alt="">
          <div class="l-text">长条广告</div>
        </div>
        <div draggable="true" class="l-content" @dragstart='dragTemplate($event, wideTemplate[3])'>
          <img src="../../assets/floor/special.png" alt="">
          <div class="l-text">专场</div>
        </div>
        <div draggable="true" class="l-content" @dragstart='dragTemplate($event, wideTemplate[4])'>
          <img src="../../assets/floor/design.png" alt="">
          <div class="l-text">设计师</div>
        </div>
        <div draggable="true" class="l-content" @dragstart='dragTemplate($event, wideTemplate[5])'>
          <img src="../../assets/floor/like.png" alt="">
          <div class="l-text">猜你喜欢</div>
        </div>
      </div>
    </div>
    <div class="pc-right">
      <div class="nav clearfix">
        <ul class="clearfix">
          <li @click='toggleNav("home", "home")' :class="{cur: true, active: curNav === 'home'}">
            <span>首页</span>
          </li>
          <!--切换导航时，传递导航对应的频道id-->
          <div v-for="(nav, index) in navList" :key='index'>
            <li :class="{cur: true, active: curNav === nav.id}" v-if="nav.isview == '1'">
              <span @click='toggleNav(nav.id, nav.chId)'>{{nav.titleName}}</span>
              <img src="../../assets/close_r.png" class="clear_icon" @click="delNavPanel = true; delNavParams.idList = [nav.id]">
            </li>
          </div>
          <li @click='$router.push(`/navigationMange/list?three=${$route.query.three}`)'>
            <img src="../../assets/floor/add_pc.png" alt="" class="add_icon">
          </li>
        </ul>
        <span class="cur" @click="$router.push(`/navigationMange/list?three=${$route.query.three}&id=${curNav}`)" v-if="curNav != 'home'">编辑</span>
      </div>
      <banner v-if='advertList.length' :advertList='advertList' :terminal='`PC`' @refresh='_getAdvertList'></banner>
      <div class="floor">
        <div class="floor-item" v-for="(val, index) in floorList" :key="index" draggable="true" @dragstart='dragSort($event, val.id, val.gfSequence, val.wideTemplate)' @drop.prevent.stop='dropTemplate($event, val.gfSequence, val.wideTemplate)'  @dragover.prevent>
          <div class="option-floor">
            <span @click="addFloor(val.id)">编辑 |</span>
            <span @click='delPanel = true; delParams.idList = [Number(val.id)]'> 删除楼层</span>
          </div>
          <w-title :isTitle='val.isViewName == "1" && val.gfDisplay == "1"' :titleColor='val.gfCss' :title='val.gfName' :enTitle='val.enName' :keywords='val.keyWord ? val.keyWord.split(",") : []'></w-title>
          <div :class="{tempBox: val.isViewName != '1'}">
            <more-advert v-if='val.wideTemplate == wideTemplate[0] && val.gfDisplay == "1"' @on-edit='editTemp' :wideGoods='val.wideGoods || []' :floorId='val.id'></more-advert>
            <new_product v-if='val.wideTemplate == wideTemplate[1] && val.gfDisplay == "1"' @on-edit='editTemp' :wideGoods='val.wideGoods || []' :floorId='val.id'></new_product>
            <long-advert v-if='val.wideTemplate == wideTemplate[2] && val.gfDisplay == "1"' @on-edit='editTemp' :wideGoods='val.wideGoods || []' :floorId='val.id'></long-advert>
            <special v-if='val.wideTemplate == wideTemplate[3] && val.gfDisplay == "1"' @on-edit='editTemp' :wideGoods='val.wideGoods || []' :floorId='val.id' :bgColor='val.gfCss'></special>
            <designer v-if='val.wideTemplate == wideTemplate[4] && val.gfDisplay == "1"' @on-edit='editTemp' :wideGoods='val.wideGoods || []' :floorId='val.id'></designer>
            <you-like v-if='val.wideTemplate == wideTemplate[5] && val.gfDisplay == "1"' @on-edit='editTemp' :wideGoods='val.wideGoods || []' :floorId='val.id'></you-like>
          </div>
        </div>
        <div class="add-btn">
          <w-button @on-click='addFloor'>新增楼层</w-button>
        </div>
      </div>
    </div>

    <!-- 删除楼层 -->
    <w-panel-fixed-wrap v-model="delPanel"  :panel-title="true" title="删除楼层" :width="`260px`" :height="`200px`" @on-confirm='delOption'>
      <div class="panel-classify">
        是否确认删除该楼层
      </div>
    </w-panel-fixed-wrap>

    <!-- 删除导航 -->
    <w-panel-fixed-wrap v-model="delNavPanel" :panel-title="true" title="删除导航" :width="`260px`" :height="`200px`" @on-confirm='delNavOption'>
      <div class="panel-classify">
        是否确认删除该导航
      </div>
    </w-panel-fixed-wrap>
  </div>
</template>

<script>
import MoreAdvert from './components/moreAdvert'
import NewProduct from './components/newProduct'
import LongAdvert from './components/longAdvert'
import SpecialField from './components/SpecialField'
import Designer from './components/Designer'
import YouLike from './components/youLike'
import Banner from './components/banner'
import Title from './components/title'
import { apiFloorMange, apiDecorateMange } from 'js/api'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      delPanel: false,
      delNavPanel: false,
      // 模板数组，共6种
      wideTemplate: ['adv_more', 'new_product', 'advinfo', 'special', 'designer', 'you_like'],
      curChannel: this.$route.query.curChannel || 'home', // 当前频道，导航对应频道，目前一个导航对应一个频道
      curNav: this.$route.query.curNav || 'home', // 当前导航
      navList: [],
      advertList: [],
      floorList: [],
      isAppLike: false,
      // 查询导航列表 -- 参数
      queryParams: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        currentPage: 1,
        showCount: 999
      },
      // 查询楼层 -- 参数
      queryFloor: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        deviceType: 'PC', // 查询首页楼层 -- 需要
        channelId: '', // 查询频道楼层 -- 需要
        currentPage: 1,
        showCount: 15
      },
      // 删除楼层 -- 参数
      delParams: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        idList: []
      },
      // 添加楼层 -- 参数
      addParams: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        gfCss: 'f00384',
        deviceType: 'PC', // 添加首页楼层 -- 需要
        cfChId: '', // 添加频道楼层 -- 需要
        gfSequence: '', // 添加首页楼层 -- 需要
        cfSequence: '', // 添加频道楼层 -- 需要
        id: '',
        gfDisplay: '1',
        disPlay: '1',
        wideTemplate: '',
        oldSequence: '',
        nowSequence: ''
      },
      // 查询广告 -- 参数
      queryAdvert: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        advId: '',
        currentPage: 1,
        showCount: 999
      },
      // 添加广告 -- 参数
      advertParams: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        adApId: ''
      },
      // 删除 导航 -- 参数
      delNavParams: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        idList: []
      }
    }
  },
  components: {
    'more-advert': MoreAdvert,
    'new_product': NewProduct,
    'long-advert': LongAdvert,
    'special': SpecialField,
    'designer': Designer,
    'you-like': YouLike,
    'banner': Banner,
    'w-title': Title
  },
  created() {
    this._getNavList()
    this._getFloorList(this.curChannel)
  },
  computed: {
    ...mapGetters(['token'])
  },
  watch: {
    '$route'() {
      if (!this.$route.query.curChannel) {
        this.curChannel = 'home'
        this.curNav = 'home'
      } else {
        this.curChannel = this.$route.query.curChannel
        this.curNav = this.$route.query.curNav
      }
      this._getFloorList(this.curChannel)
    }
  },
  methods: {
    // 获取 导航列表
    _getNavList () {
      this.queryParams.accessToken = this.token
      apiDecorateMange.getNavList(this.queryParams).then(data => {
        if (data.code != 200) return
        this.navList = data.data.recordList
      })
    },
    // 获取 楼层列表
    _getFloorList(type) {
      this.floorList = []
      this.curChannel = type
      this.queryFloor.accessToken = this.token
      if (this.curChannel == 'home') {
        this.queryFloor.deviceType = 'PC'
        this.queryFloor.channelId = ''
        apiFloorMange.queryHFloorList(this.queryFloor).then(data => {
          const list = data.data.recordList || []
          this.floorList = list.map(item => {
            return {
              deviceType: item.deviceType,
              enName: item.enName || '',
              gfDisplay: item.gfDisplay || '0',
              isViewName: item.isViewName || '0',
              gfCss: item.gfCss || 'f00384',
              gfName: item.gfName || '',
              gfSequence: item.gfSequence,
              id: item.id,
              keyWord: item.keyWord || '',
              wideGoods: item.wideGoods ? JSON.parse(item.wideGoods) : '',
              wideTemplate: item.wideTemplate
            }
          })
          for (let i = 0; i < this.floorList.length; i++) {
            // 当模板类型为 category，判断 left right 是否有值
            if (this.floorList[i].wideTemplate == 'category') {
              for (let j = 0; j < 2; j++) {
                if (this.floorList[i].wideGoods) {
                  if (this.floorList[i].wideGoods.CategoryList[j].direction == 'left') {
                    this.floorList[i].wideGoods.left = this.floorList[i].wideGoods.CategoryList[j]
                  }
                  if (this.floorList[i].wideGoods.CategoryList[j].direction == 'right') {
                    this.floorList[i].wideGoods.right = this.floorList[i].wideGoods.CategoryList[j]
                  }
                }
              }
            }
            // 判断是否有 猜你喜欢 楼层
            if (this.floorList[i].wideTemplate == 'you_like') {
              this.isAppLike = true
            }
          }
        })
        // pc首页的 广告位id 固定 -1
        this.queryAdvert.advId = '-1'
        this._getAdvertList()
      } else {
        this.queryFloor.deviceType = ''
        this.queryFloor.channelId = this.curChannel
        apiFloorMange.queryCFloorList(this.queryFloor).then(data => {
          const list = data.data.recordList || []
          // 重组 floorList,首页和频道 楼层 参数统一
          this.floorList = list.map(item => {
            return {
              deviceType: 'PC',
              enName: '',
              gfDisplay: item.disPlay || '0',
              isViewName: item.isViewName || '0',
              gfCss: item.gfCss || 'f00384',
              gfName: item.cfName || '',
              gfSequence: item.cfSequence,
              id: item.id,
              keyWord: item.keyWord || '',
              wideGoods: item.wideGoods ? JSON.parse(item.wideGoods) : '',
              wideTemplate: item.wideTemplate
            }
          })
          for (let i = 0; i < this.floorList.length; i++) {
            // 当模板类型为 category，判断 left right 是否有值
            if (this.floorList[i].wideTemplate == 'category') {
              for (let j = 0; j < 2; j++) {
                if (this.floorList[i].wideGoods) {
                  if (this.floorList[i].wideGoods.CategoryList[j].direction == 'left') {
                    this.floorList[i].wideGoods.left = this.floorList[i].wideGoods.CategoryList[j]
                  }
                  if (this.floorList[i].wideGoods.CategoryList[j].direction == 'right') {
                    this.floorList[i].wideGoods.right = this.floorList[i].wideGoods.CategoryList[j]
                  }
                }
              }
            }
            // 判断是否有 猜你喜欢 楼层
            if (this.floorList[i].wideTemplate == 'you_like') {
              this.isAppLike = true
            }
          }
        })
        // 根据频道 id 获取到 广告位 id
        const par = {
          accessToken: this.token,
          threeMenuCode: this.$route.query.three || '',
          id: this.curChannel
        }
        apiDecorateMange.getChannelInfo(par).then(data => {
          if (data.code != 200) return
          this.queryAdvert.advId = data.data.channelInfo.advPosId || ''
          this._getAdvertList()
        })
      }
    },
    // 获取广告 列表
    _getAdvertList() {
      this.queryAdvert.accessToken = this.token
      apiDecorateMange.getAdvertList(this.queryAdvert).then(data => {
        this.advertList = data.data.recordList || []
      })
    },
    // 添加 广告
    addAdvert() {
      this.advertParams.accessToken = this.token
      this.advertParams.adApId = this.queryAdvert.advId
      apiDecorateMange.addAdvert(this.advertParams).then(data => {
        if (data.code != 200) return
        this.$toast('广告新增成功', () => {
          this._getAdvertList()
        })
      })
    },
    // 导航 切换
    toggleNav(navid, chid) {
      this.$router.push(`/homeDecorate/pc?three=${this.$route.query.three}&cIndex=${this.$route.query.cIndex}&curChannel=${chid}&curNav=${navid}`)
    },
    // 编辑楼层模板
    editTemp(id, temp, pos) {
      this.$router.push(`/homeDecorate/edit?three=${this.$route.query.three}&wideTemplate=${temp}&id=${id}&pos=${pos}&curChannel=${this.curChannel}`)
    },
    // 新增/编辑楼层 跳转
    addFloor(id) {
      if (this.curChannel == 'home') {
        if (id) {
          this.$router.push(`/floorMange/add?three=${this.$route.query.three}&id=${id}&terminal=PC`)
        } else {
          this.$router.push(`/floorMange/add?three=${this.$route.query.three}&terminal=PC`)
        }
      } else {
        if (id) {
          this.$router.push(`/floorMange/cAdd?three=${this.$route.query.three}&id=${id}&terminal=PC`)
        } else {
          this.$router.push(`/floorMange/cAdd?three=${this.$route.query.three}&terminal=PC&chId=${this.curChannel}`)
        }
      }
    },
    // 开始拖动 模板
    dragTemplate(event, temp) {
      event.dataTransfer.setData('temp', temp)
      this.addParams.id = ''
      this.addParams.oldSequence = ''
    },
    // 拖动排序
    dragSort(event, id, sequence, temp) {
      // 猜你喜欢 需要在楼层的最后，不能拖动
      if (temp == 'you_like') return
      event.dataTransfer.setData('temp', temp)
      this.addParams.id = Number(id)
      this.addParams.oldSequence = sequence
    },
    // 模板 停止拖动
    dropTemplate(event, index, targetTemp) {
      let temp = event.dataTransfer.getData('temp')
      // 如果添加的是banner,则给当前频道添加广告
      if (temp === 'banner') {
        this.addAdvert()
        return
      }
      // 当拖动的模板为 猜你喜欢，模板放到楼层的最后
      if (temp == 'you_like') {
        let lastIndex = 0
        if (this.floorList.length) {
          lastIndex = Number(this.floorList[this.floorList.length -1].gfSequence) + 1
        }
        this.submitAddFloor(lastIndex, temp)
        return
      }
      // 如果触发的是装修页面根元素身上的drop事件，则index===undefined，表明楼层添加在频道列表的最后，由此拿到楼层的序号
      if (index===undefined) {
        // 楼层添加在列表最后，需要拿到 最后一个楼层的排序
        let lastIndex = 0
        if (this.floorList.length) {
          if (this.isAppLike) { // 当有 猜你喜欢 模板时，新增到倒数第二个
            if (this.floorList.length > 1) {
              lastIndex = Number(this.floorList[this.floorList.length -2].gfSequence) + 1
            }
          } else {
            lastIndex = Number(this.floorList[this.floorList.length -1].gfSequence) + 1
          }
        }
        if (this.addParams.id) { // 拖动排序时
          lastIndex--
        }
        this.submitAddFloor(lastIndex, temp)
      } else {
        // dirction指示鼠标的落点在drop元素的上半区还是下半区
        let direction = 'up'
        let mouseY = event.clientY
        let elY = event.currentTarget.getBoundingClientRect().top
        let height = event.currentTarget.clientHeight
        // 判断鼠标落点在drop元素的位置
        if (mouseY - elY > (height / 2) && targetTemp != 'you_like') { 
          direction = 'down'
        }
        if (direction === 'down') {
          index++
        }
        if (this.addParams.id && targetTemp == 'you_like') {
          index--
        }
        this.submitAddFloor(index, temp)
      }
    },
    // 提交 楼层 添加
    submitAddFloor(gfSequence, temp) {
      if (!temp) return
      this.addParams.accessToken = this.token
      this.addParams.cfChId = this.curChannel == 'home' ? '' : this.curChannel
      this.addParams.deviceType = this.curChannel == 'home' ? 'PC' : ''
      this.addParams.wideTemplate = temp
      if (this.curChannel == 'home') {
        this.addParams.nowSequence = this.addParams.gfSequence = String(gfSequence)
        this.addParams.cfSequence = ''
        apiFloorMange.addHFloor(this.addParams).then(data => {
          if (data && data.code != 200) return
          if (!this.addParams.id) {
            this.$toast('首页楼层添加成功', () => {
              this._getFloorList('home')
            })
          } else {
            this._getFloorList('home')
          }
        })
      } else {
        this.addParams.nowSequence = this.addParams.cfSequence = String(gfSequence)
        this.addParams.gfSequence = ''
        apiFloorMange.addCFloor(this.addParams).then(data => {
          if (data && data.code != 200) return
          if (!this.addParams.id) {
            this.$toast('频道楼层添加成功', () => {
              this._getFloorList(this.curChannel)
            })
          } else {
            this._getFloorList(this.curChannel)
          }
        })
      }
    },
    // 删除楼层
    delOption() {
      this.delParams.accessToken = this.token
      if (this.curChannel == 'home') {
        apiFloorMange.delHFloor(this.delParams).then(data => {
          if (data.code != 200) return
          this.$toast('楼层删除成功', () => {
            this.delPanel = false
            this._getFloorList('home')
          })
        })
      } else {
        apiFloorMange.delCFloor(this.delParams).then(data => {
          if (data.code != 200) return
          this.$toast('楼层删除成功', () => {
            this.delPanel = false
            this._getFloorList(this.curChannel)
          })
        })
      }
    },
    // 删除导航
    delNavOption() {
      this.delNavParams.accessToken = this.token
      apiDecorateMange.delNav(this.delNavParams).then(data => {
        if (data.code != 200) return
        this.$toast('删除成功', () => {
          this.delNavPanel = false
          this.toggleNav('home', 'home')
          this._getNavList()
        })
      })
    }
  }
}
</script>

<style lang='scss' scoped>
@import '../../scss/_var.scss';
.pc-left {
  width: 290px;
  height: 1059px;
  float: left;
  border: 1px solid $border-gray-light;
  .l-head {
    height: 38px;
    line-height: 38px;
    background: $color-main;
    padding-left: 10px;
    color: #fff;
  }
  .l-item {
    padding: 0 14px;
    .l-title {
      margin: 10px 0;
    }
    .l-text {
      text-align: center;
      margin: 10px 0;
      font-size: 12px;
    }
  }
}
.pc-right {
  width: 880px;
  float: right;
  position: relative;
  border: 1px solid $border-gray-light;
  .nav {
    line-height: 30px;
    border-bottom: 1px solid $border-gray-light;
    ul {
      li {
        float: left;
        padding: 0 10px;
        font-size: 12px;
        .clear_icon {
          width: 14px;
          height: 14px;
          position: relative;
          top: -6px;
          left: -6px;
        }
        .add_icon {
          width: 30px;
          height: 19px;
          cursor: pointer;
          margin-top: 5px;
        }
        &.active{
          color: $color-main;
        }
      }
    }
    & > span {
      float: right;
      margin-right: 20px;
      color: $color-main;
    }
  }
  .banner {
    width: 100%;
    height: 194px;
    position: relative;
    button {
      width: 40px;
      height: 20px;
      border-radius: 10px;
      background: $color-main;
      position: absolute;
      top: 10px;
      right: 10px;
      color: #fff;
      font-size: 12px;
    }
  }
}
.floor {
  width: 565px;
  margin: 0 auto;
  .floor-item {
    width: 100%;
    .option-floor {
      position: absolute;
      right: 20px;
      color: $color-main;
      cursor: pointer;
      font-size: 12px;
    }
    .tempBox {
      margin-top: 25px;
    }
  }
  .add-btn {
    text-align: right;
    padding: 20px 0;
  }
}
</style>
